var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
let { getUrlImg, FormatData } = require('../util/comm/comm.js');
let { isUser, registerUser, isLogin, newsList, swiperList, newsInfo, isaddCollection, isaddWatch, addNewsCollection, changeNewsCollection,
  delNewsCollection, commList, isaddCommCollection, addCommCollection, changeCommCollection, delCommCollection, addComment, commentId, addWatch,
  addIntegral, changeNewsWatch, userNewsSave
} = require('../mysql/user');
let { adminById, userById, typeListAll } = require('../mysql/admin');

router.post('/loginregister', upload.single('userUrl'), async (req, res, next) => {
  let { userName, userPass, userSex, userUrl } = req.body;
  userUrl = getUrlImg(req)
  let jsonData = {}
  let data = await isUser({
    userName
  })
  if (data.length) {
    jsonData = {
      code: 0,
      data: '该用户名已存在'
    }
  } else {
    let { affectedRows } = await registerUser({
      userName, userPass, userSex, userUrl
    })
    if (affectedRows) {
      jsonData = {
        code: 1,
        data: data[0]
      }
      req.session.userInfo = data[0]
    }
    else {
      jsonData = {
        code: 0,
        data: "注册失败"
      }
    }
  }
  return res.json(jsonData)
});

router.post('/islogin', async (req, res, next) => {
  let { userName, userPass, captcha } = req.body;
  let jsonData = {};
  console.log(req)
  const sessionCaptcha = req.session.captcha.toLowerCase();
  // if (sessionCaptcha != captcha) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isLogin({
    userName, userPass
  })
  if (!data.length) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误",
    }
  } else {
    jsonData = {
      code: 1,
      data: data[0]
    }
    req.session.userInfo = data[0]
  }
  return res.json(jsonData)
});

router.post('/uploadImg', upload.single('file'), async (req, res, next) => {
  let url = getUrlImg(req);
  res.json({
    code: 200,
    data: { url: url },
    url: url,
    msg: "success"
  })
})

router.post('/newsList', async (req, res, next) => {
  let { page, limit, newsId, newsTitle, newsType } = req.body;
  var num = (page - 1) * limit;
  let { data, count } = await newsList(num, limit, {
    newsId, newsTitle, newsType
  });

  await new Promise(async (resolve, reject) => {
    let promiseList = data.map((item) => {
      return new Promise(async (res, rej) => {
        if (item.userIdentity == 'admin') {
          let [{ adminName }] = await adminById(item.userId)
          item.userName = adminName
        } else {
          let [{ userName }] = await userById(item.userId)
          item.userName = userName
        }
        res()
      })
    })
    await Promise.all(promiseList)
    resolve()
  })

  if (data.length) {
    res.json({
      code: 1,
      data: FormatData(data, {
        newsImg: 'json'
      }),
      count: count
    })
  } else {
    res.json({
      code: 0,
      msg: "数据加载完毕",
      count: count
    })
  }

});

router.post('/swiperList', async (req, res, next) => {
  let { data, count } = await swiperList();
  if (data.length) {
    res.json({
      code: 1,
      data: data,
      count: count
    })
  } else {
    res.json({
      code: 0,
      msg: "数据加载完毕",
      count: count
    })
  }
});

router.post('/newsInfo', async (req, res, next) => {
  let { newsId } = req.body;
  let data = await newsInfo(newsId);
  let item = data[0]
  if (item.userIdentity == 'admin') {
    let [{ adminName }] = await adminById(item.userId)
    item.userName = adminName
  } else {
    let [{ userName }] = await userById(item.userId)
    item.userName = userName
  }

  if (req.session.userInfo) {
    let { userId } = req.session.userInfo
    let Collection = await isaddCollection({
      userId, newsId
    })
    let Watch = await isaddWatch({
      userId, newsId
    })
    item.isWatch = Boolean(Watch.length)
    item.isCollection = Boolean(Collection.length)
  } else {
    item.isWatch = false
    item.isCollection = false
  }

  res.json({
    code: 1,
    data: FormatData(item, {
      newsImg: 'json'
    })
  })
})

router.post('/addCollection', async (req, res, next) => {
  let { type, id, userId } = req.body
  if (type == 'news') {
    await addNewsCollection({
      newsId: id,
      userId: userId
    })
    await changeNewsCollection({
      newsCollection: 1,
      newsId: id
    })
    res.json({
      code: 1,
      data: {
        info: "点赞成功",
        flog: 0
      }
    })
  } else {
    await addCommCollection({
      commId: id,
      userId: userId
    })
    await changeCommCollection({
      commCollection: 1,
      commId: id
    })
    res.json({
      code: 1,
      data: {
        info: "点赞成功",
        flog: 0
      }
    })
  }
})

router.post('/delCollection', async (req, res, next) => {
  let { type, id, userId } = req.body
  if (type == 'news') {
    await delNewsCollection({
      newsId: id,
      userId: userId
    })
    await changeNewsCollection({
      newsCollection: -1,
      newsId: id
    })
    res.json({
      code: 1,
      data: {
        info: "取消点赞成功",
        flog: 0
      }
    })
  } else {
    await delCommCollection({
      commId: id,
      userId: userId
    })
    await changeCommCollection({
      commCollection: -1,
      commId: id,
    })
    res.json({
      code: 1,
      data: {
        info: "取消点赞成功",
        flog: 0
      }
    })
  }
})

router.post('/commList', async (req, res, next) => {
  let { page, limit, newsId } = req.body;
  var num = (page - 1) * limit;
  let { data, count } = await commList(num, limit, { newsId });

  await new Promise(async (resolve, reject) => {
    let promiseList = data.map((item) => {
      return new Promise(async (res, rej) => {
        let [{ userName, userUrl }] = await userById(item.userId)
        item.userName = userName
        item.userUrl = userUrl
        if (req.session.userInfo) {
          let { userId } = req.session.userInfo
          let Collection = await isaddCommCollection({
            userId, commId: item.commId
          })
          item.isCollection = Boolean(Collection.length)
        } else {
          item.isCollection = false
        }
        res()
      })
    })
    await Promise.all(promiseList)
    resolve()
  })

  if (data.length) {
    res.json({
      code: 1,
      data: data,
      count: count
    })
  } else {
    res.json({
      code: 0,
      msg: "数据加载完毕",
      count: count
    })
  }

});

router.post('/addComment', async (req, res, next) => {
  let { userId, newsId, commCom } = req.body;
  let { insertId } = await addComment({
    userId, newsId, commCom
  })
  let [data] = await commentId(insertId)
  res.json({
    code: 1,
    data: data
  })
});

router.post('/addWatch', async (req, res, next) => {
  let { userId, newsId, newsIntegral } = req.body;
  await addWatch({
    userId, newsId
  })
  await addIntegral({
    userIntegral: newsIntegral,
    userId: userId
  })
  await changeNewsWatch({
    newsWatch: 1,
    newsId: newsId
  })
  res.json({
    code: 1,
    data: "阅读领取积分成功"
  })
});

router.post('/typeListAll', async (req, res, next) => {
  let data = await typeListAll()
  res.json({
    code: 1,
    data
  })
})

router.post('/userNewsSave', async (req, res, next) => {
  let { userId, userIdentity, newsState, newsTitle, newsType, newsIntegral, newsTime, newContent, newsImg } = req.body;
  userId = req.session.userInfo.userId
  userIdentity = 'user'
  newsState = '0'
  newsImg = JSON.stringify(newsImg)
  let { affectedRows } = await userNewsSave({
    userId, userIdentity, newsState, newsTitle, newsType, newsIntegral, newsTime, newContent, newsImg
  })
  if (affectedRows) {
    res.json({
      code: 1
    })
  } else {
    res.json({
      code: 0,
      msg: '添加失败'
    })
  }
})
module.exports = router;
